// 环境配置管理模块
class EnvironmentManager {
    constructor() {
        this.environmentTypes = [];
        this.projectConfigs = [];
        this.currentEditingEnvType = null;
        this.currentEditingProject = null;
        // 不在构造函数中调用init，而是延迟调用
    }

    async init() {
        await this.loadData();
        this.bindEvents();
        this.render();
        // 默认选中项目配置标签
        this.switchConfigTab('projects');
    }

    // 渲染环境配置界面
    render() {
        this.renderEnvTypes();
        this.renderProjects();
        this.renderProjectEnvironments();
    }

    async loadData() {
        try {
            console.log('[环境配置] 开始加载环境配置数据...');
            const response = await fetch('/api/environment');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const config = await response.json();
            console.log('[环境配置] 获取到配置数据:', config);
            this.environmentTypes = config.environmentTypes || [];
            this.projectConfigs = config.projectConfigs || [];
            console.log('[环境配置] 环境类型数量:', this.environmentTypes.length);
            console.log('[环境配置] 项目配置数量:', this.projectConfigs.length);
        } catch (error) {
            console.error('加载环境配置失败:', error);
            // 使用默认配置
            this.environmentTypes = [
                { name: 'local', displayName: '本机环境' },
                { name: 'dev', displayName: '开发环境' },
                { name: 'qa', displayName: '测试环境' },
                { name: 'uat', displayName: '预发布环境' },
                { name: 'prod', displayName: '生产环境' }
            ];
            this.projectConfigs = [];
            console.log('[环境配置] 使用默认配置');
        }
    }

    // 保存环境类型到后端
    async saveEnvTypes() {
        try {
            const configData = {
                environmentTypes: this.environmentTypes,
                projectConfigs: this.projectConfigs
            };
            console.log('[环境配置] 准备保存的环境配置数据:', configData);
            const response = await fetch('/api/environment', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(configData)
            });
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            console.log('[环境配置] 环境类型保存成功');
        } catch (error) {
            console.error('保存环境类型失败:', error);
        }
    }

    // 保存项目配置到后端
    async saveProjects() {
        try {
            const configData = {
                environmentTypes: this.environmentTypes,
                projectConfigs: this.projectConfigs
            };
            console.log('[环境配置] 准备保存的项目配置数据:', configData);
            const response = await fetch('/api/environment', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(configData)
            });
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
        } catch (error) {
            console.error('保存项目配置失败:', error);
        }
    }

    // 绑定事件
    bindEvents() {
        // 标签页切换事件
        const configTabs = document.querySelectorAll('.config-tab');
        configTabs.forEach(tab => {
            tab.addEventListener('click', () => {
                this.switchConfigTab(tab.dataset.tab);
            });
        });

        // 添加环境类型按钮
        document.getElementById('add-env-type').addEventListener('click', () => {
            this.showEnvTypeModal();
        });

        // 添加项目按钮
        document.getElementById('add-project').addEventListener('click', () => {
            this.showProjectModal();
        });

        // 恢复默认配置按钮
        document.getElementById('restore-default-env-types').addEventListener('click', () => {
            this.restoreDefaultEnvTypes();
        });

        // 导出环境配置按钮（全局绑定）
        if (document.getElementById('export-environment')) {
            document.getElementById('export-environment').addEventListener('click', () => {
                if (window.environmentManager) {
                    window.environmentManager.exportEnvironment();
                }
            });
        }

        // 导入环境配置按钮（全局绑定）
        if (document.getElementById('import-environment')) {
            document.getElementById('import-environment').addEventListener('click', () => {
                if (window.environmentManager) {
                    window.environmentManager.importEnvironment();
                }
            });
        }
    }

    // 切换配置标签页
    switchConfigTab(tabName) {
        // 隐藏所有标签页内容
        const tabContents = document.querySelectorAll('.config-tab-content');
        tabContents.forEach(content => {
            content.classList.remove('active');
        });

        // 移除所有标签页的激活状态
        const tabs = document.querySelectorAll('.config-tab');
        tabs.forEach(tab => {
            tab.classList.remove('active');
        });

        // 显示选中的标签页内容
        const activeContent = document.getElementById(`${tabName}-tab-content`);
        if (activeContent) {
            activeContent.classList.add('active');
        }

        // 激活选中的标签页
        const activeTab = document.querySelector(`.config-tab[data-tab="${tabName}"]`);
        if (activeTab) {
            activeTab.classList.add('active');
        }
    }

    // 渲染环境类型列表
    renderEnvTypes() {
        const container = document.getElementById('env-types-list');
        if (!container) return;
        
        container.innerHTML = '';

        if (this.environmentTypes.length === 0) {
            container.innerHTML = '<div class="empty-state">暂无环境类型配置</div>';
            return;
        }

        this.environmentTypes.forEach(envType => {
            const item = document.createElement('div');
            item.className = 'env-type-item';
            item.innerHTML = `
                <div class="env-type-info">
                    <span class="env-type-name">${envType.name}</span>
                    <span class="env-type-display">${envType.displayName}</span>
                </div>
                <div class="env-type-actions">
                    <button class="btn btn-small" onclick="environmentManager.editEnvType('${envType.name}')">编辑</button>
                    <button class="btn btn-small btn-danger" onclick="environmentManager.deleteEnvType('${envType.name}')">删除</button>
                </div>
            `;
            container.appendChild(item);
        });
    }

    // 渲染项目列表
    renderProjects() {
        const container = document.getElementById('projects-list');
        if (!container) return;
        
        container.innerHTML = '';

        if (this.projectConfigs.length === 0) {
            container.innerHTML = '<div class="empty-state">暂无项目配置</div>';
            return;
        }

        this.projectConfigs.forEach(project => {
            const item = document.createElement('div');
            item.className = 'project-item';
            
            // 将环境配置数组转换为显示字符串
            const envList = (project.environments || [])
                .map(env => `<span class="env-tag">${env.environment}: ${env.baseUrl}</span>`)
                .join('');

            item.innerHTML = `
                <div class="project-info">
                    <div class="project-header">
                        <span class="project-name">${project.name}</span>
                        <span class="project-context">${project.contextPath}</span>
                    </div>
                    <div class="project-environments">
                        ${envList}
                    </div>
                </div>
                <div class="project-actions">
                    <button class="btn btn-small" onclick="environmentManager.editProject('${project.name}')">编辑</button>
                    <button class="btn btn-small btn-danger" onclick="environmentManager.deleteProject('${project.name}')">删除</button>
                </div>
            `;
            container.appendChild(item);
        });
    }

    // 显示环境类型编辑模态框
    showEnvTypeModal(envTypeName = null) {
        this.currentEditingEnvType = envTypeName;
        const modal = document.getElementById('env-type-modal');
        const title = document.getElementById('env-type-modal-title');
        const nameInput = document.getElementById('env-type-name');
        const displayInput = document.getElementById('env-type-display');

        if (envTypeName) {
            const envType = this.environmentTypes.find(e => e.name === envTypeName);
            if (envType) {
                title.textContent = '编辑环境类型';
                nameInput.value = envType.name;
                displayInput.value = envType.displayName;
            }
        } else {
            title.textContent = '添加环境类型';
            nameInput.value = '';
            displayInput.value = '';
        }

        modal.style.display = 'flex';
    }

    // 显示项目编辑模态框
    showProjectModal(projectName = null) {
        this.currentEditingProject = projectName;
        const modal = document.getElementById('project-modal');
        const title = document.getElementById('project-modal-title');
        const nameInput = document.getElementById('project-name');
        const contextInput = document.getElementById('project-context');

        if (projectName) {
            const project = this.projectConfigs.find(p => p.name === projectName);
            if (project) {
                title.textContent = '编辑项目';
                nameInput.value = project.name;
                contextInput.value = project.contextPath;
            }
        } else {
            title.textContent = '添加项目';
            nameInput.value = '';
            contextInput.value = '';
        }

        this.renderProjectEnvironments();
        modal.style.display = 'flex';
    }

    // 渲染项目环境配置
    renderProjectEnvironments() {
        const container = document.getElementById('project-environments');
        if (!container) return;
        
        container.innerHTML = '';

        const project = this.currentEditingProject ? 
            this.projectConfigs.find(p => p.name === this.currentEditingProject) : null;

        this.environmentTypes.forEach(envType => {
            const envDiv = document.createElement('div');
            envDiv.className = 'env-config-item';
            
            // 从环境配置数组中查找当前环境类型的URL
            let currentUrl = '';
            if (project && project.environments) {
                const envConfig = project.environments.find(env => env.environment === envType.name);
                if (envConfig) {
                    currentUrl = envConfig.baseUrl;
                }
            }

            envDiv.innerHTML = `
                <label>${envType.displayName} (${envType.name}):</label>
                <input type="text" 
                       data-env="${envType.name}" 
                       placeholder="如: http://localhost:8080" 
                       value="${currentUrl}">
            `;
            container.appendChild(envDiv);
        });
    }

    // 编辑环境类型
    editEnvType(envTypeName) {
        this.showEnvTypeModal(envTypeName);
    }

    // 删除环境类型
    deleteEnvType(envTypeName) {
        if (confirm('确定要删除这个环境类型吗？')) {
            this.environmentTypes = this.environmentTypes.filter(e => e.name !== envTypeName);
            this.saveEnvTypes();
            this.renderEnvTypes();
            
            // 同时从所有项目中移除这个环境类型 - 使用数组filter方法
            this.projectConfigs.forEach(project => {
                if (project.environments) {
                    project.environments = project.environments.filter(env => env.environment !== envTypeName);
                }
            });
            this.saveProjects();
            this.renderProjects();
        }
    }

    // 编辑项目
    editProject(projectName) {
        this.showProjectModal(projectName);
    }

    // 删除项目
    deleteProject(projectName) {
        if (confirm('确定要删除这个项目配置吗？')) {
            this.projectConfigs = this.projectConfigs.filter(p => p.name !== projectName);
            this.saveProjects();
            this.renderProjects();
        }
    }

    // 保存环境类型
    saveEnvType() {
        const nameInput = document.getElementById('env-type-name');
        const displayInput = document.getElementById('env-type-display');
        
        const name = nameInput.value.trim();
        const displayName = displayInput.value.trim();

        if (!name || !displayName) {
            alert('请填写完整的环境类型信息');
            return;
        }

        // 检查名称是否重复
        const existingEnvType = this.environmentTypes.find(e => 
            e.name === name && e.name !== this.currentEditingEnvType
        );
        if (existingEnvType) {
            alert('环境类型名称已存在');
            return;
        }

        if (this.currentEditingEnvType) {
            // 编辑现有环境类型
            const envType = this.environmentTypes.find(e => e.name === this.currentEditingEnvType);
            if (envType) {
                const oldName = envType.name;
                envType.name = name;
                envType.displayName = displayName;
                
                // 更新项目中的环境配置
                if (oldName !== name) {
                    this.projectConfigs.forEach(project => {
                        if (project.environments && project.environments[oldName]) {
                            project.environments[name] = project.environments[oldName];
                            delete project.environments[oldName];
                        }
                    });
                    this.saveProjects();
                }
            }
        } else {
            // 添加新环境类型
            const newEnvType = {
                name: name,
                displayName: displayName
            };
            this.environmentTypes.push(newEnvType);
        }

        this.saveEnvTypes();
        this.renderEnvTypes();
        this.closeEnvTypeModal();
    }

    // 保存项目
    saveProject() {
        const nameInput = document.getElementById('project-name');
        const contextInput = document.getElementById('project-context');
        
        const name = nameInput.value.trim();
        const contextPath = contextInput.value.trim();

        if (!name || !contextPath) {
            alert('请填写完整的项目信息');
            return;
        }

        // 检查上下文路径是否重复
        const existingProject = this.projectConfigs.find(p => 
            p.contextPath === contextPath && p.name !== this.currentEditingProject
        );
        if (existingProject) {
            alert('上下文路径已存在');
            return;
        }

        // 收集环境配置 - 转换为数组格式以匹配服务器端要求
        const environments = [];
        const envInputs = document.querySelectorAll('#project-environments input[data-env]');
        envInputs.forEach(input => {
            const env = input.dataset.env;
            const url = input.value.trim();
            if (url) {
                environments.push({
                    environment: env,
                    baseUrl: url
                });
            }
        });

        if (this.currentEditingProject) {
            // 编辑现有项目
            const project = this.projectConfigs.find(p => p.name === this.currentEditingProject);
            if (project) {
                project.name = name;
                project.contextPath = contextPath;
                project.environments = environments;
            }
        } else {
            // 添加新项目
            const newProject = {
                name: name,
                contextPath: contextPath,
                environments: environments
            };
            this.projectConfigs.push(newProject);
        }

        this.saveProjects();
        this.renderProjects();
        this.closeProjectModal();
    }

    // 关闭环境类型模态框
    closeEnvTypeModal() {
        const modal = document.getElementById('env-type-modal');
        if (modal) modal.style.display = 'none';
        this.currentEditingEnvType = null;
    }

    // 关闭项目模态框
    closeProjectModal() {
        const modal = document.getElementById('project-modal');
        if (modal) modal.style.display = 'none';
        this.currentEditingProject = null;
    }

    // 根据上下文路径获取项目配置
    getProjectByContext(contextPath) {
        return this.projectConfigs.find(p => p.contextPath === contextPath);
    }

    // 从URL中提取上下文路径
    extractContextFromUrl(url) {
        try {
            const urlObj = new URL(url);
            const pathParts = urlObj.pathname.split('/').filter(part => part);
            return pathParts.length > 0 ? pathParts[0] : null;
        } catch (e) {
            return null;
        }
    }

    // 从URL中提取基础地址
    extractBaseUrlFromUrl(url) {
        try {
            const urlObj = new URL(url);
            return `${urlObj.protocol}//${urlObj.host}`;
        } catch (e) {
            return null;
        }
    }

    // 根据基础地址匹配环境
    matchEnvironmentByBaseUrl(project, baseUrl) {
        if (!project.environments) return null;
        
        // 遍历环境配置数组查找匹配的基础地址
        const envConfig = project.environments.find(env => env.baseUrl === baseUrl);
        return envConfig ? envConfig.environment : null;
    }

    // 替换URL中的基础地址
    replaceBaseUrl(originalUrl, newBaseUrl) {
        try {
            const urlObj = new URL(originalUrl);
            const newUrlObj = new URL(newBaseUrl);
            
            return `${newUrlObj.protocol}//${newUrlObj.host}${urlObj.pathname}${urlObj.search}${urlObj.hash}`;
        } catch (e) {
            return originalUrl;
        }
    }

    // 恢复默认环境类型配置
    restoreDefaultEnvTypes() {
        if (confirm('确定要恢复为默认环境类型配置吗？当前配置将被覆盖。')) {
            // 设置默认环境类型
            this.environmentTypes = [
                { name: 'local', displayName: '本机环境' },
                { name: 'dev', displayName: '开发环境' },
                { name: 'qa', displayName: '测试环境' },
                { name: 'uat', displayName: '预发布环境' },
                { name: 'prod', displayName: '生产环境' }
            ];
            
            // 保存到后端
            this.saveEnvTypes();
            
            // 更新UI
            this.renderEnvTypes();
            
            alert('默认环境类型配置已恢复');
        }
    }

    // 导出环境配置
    exportEnvironment() {
        const exportData = {
            environmentTypes: this.environmentTypes,
            projectConfigs: this.projectConfigs
        };
        const data = JSON.stringify(exportData, null, 2);
        const blob = new Blob([data], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'hermes-environment.json';
        a.click();
        URL.revokeObjectURL(url);
    }

    // 导入环境配置（去重覆盖）
    importEnvironment() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json';
        input.onchange = async (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = async (e) => {
                    try {
                        const imported = JSON.parse(e.target.result);
                        
                        // 导入环境类型（根据名称去重覆盖）
                        if (imported.environmentTypes && Array.isArray(imported.environmentTypes)) {
                            // 创建现有环境类型的Map以支持快速查找
                            const existingEnvTypesMap = new Map();
                            this.environmentTypes.forEach(env => {
                                existingEnvTypesMap.set(env.name, env);
                            });
                            
                            // 合并导入的环境类型（新的覆盖旧的）
                            imported.environmentTypes.forEach(env => {
                                existingEnvTypesMap.set(env.name, env);
                            });
                            
                            // 转换回数组
                            this.environmentTypes = Array.from(existingEnvTypesMap.values());
                        }
                        
                        // 导入项目配置（根据上下文路径去重覆盖）
                        if (imported.projectConfigs && Array.isArray(imported.projectConfigs)) {
                            // 创建现有项目配置的Map以支持快速查找
                            const existingProjectsMap = new Map();
                            this.projectConfigs.forEach(project => {
                                existingProjectsMap.set(project.contextPath, project);
                            });
                            
                            // 合并导入的项目配置（新的覆盖旧的）
                            imported.projectConfigs.forEach(project => {
                                existingProjectsMap.set(project.contextPath, project);
                            });
                            
                            // 转换回数组
                            this.projectConfigs = Array.from(existingProjectsMap.values());
                        }
                        
                        // 保存到后端
                        await this.saveEnvTypes();
                        
                        // 更新UI
                        this.render();
                        
                        alert('环境配置导入成功');
                    } catch (err) {
                        alert('环境配置导入失败: ' + err.message);
                    }
                };
                reader.readAsText(file);
            }
        };
        input.click();
    }
}

// 全局函数，供HTML中的onclick使用
function closeEnvTypeModal() {
    if (window.environmentManager) {
        window.environmentManager.closeEnvTypeModal();
    }
}

function saveEnvType() {
    if (window.environmentManager) {
        window.environmentManager.saveEnvType();
    }
}

function closeProjectModal() {
    if (window.environmentManager) {
        window.environmentManager.closeProjectModal();
    }
}

function saveProject() {
    if (window.environmentManager) {
        window.environmentManager.saveProject();
    }
}

// 全局实例
let environmentManager;

// 初始化环境管理器
document.addEventListener('DOMContentLoaded', function() {
    // 延迟初始化，确保WebView2绑定完成
    setTimeout(async () => {
        environmentManager = new EnvironmentManager();
        // 将实例暴露到全局作用域
        window.environmentManager = environmentManager;
        // 手动调用初始化
        await environmentManager.init();
    }, 1000); // 延迟1秒确保WebView2绑定完成
});